package com.test.mysqsql.basetools;

import javax.swing.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.sql.*;

public class StoreFile {

    private String dbDriver;
    private String dbURL;
    private String dbUser;
    private String dbPassword;
    private Connection con;
    private PreparedStatement ps;

    /**
     * 构造函数，初始化数据库的连接
     */
    public StoreFile() {
        dbDriver = "com.mysql.jdbc.Driver";
        dbURL = "jdbc:mysql://localhost:3306/mysql";
        dbUser = "root";
        dbPassword = "root";
        initDB();
    }

    public StoreFile(String strDriver, String strURL, String strUser, String strPwd) {
        dbDriver = strDriver;
        dbURL = strURL;
        dbUser = strUser;
        dbPassword = strPwd;
        initDB();
    }

    public static void main(String[] args) throws Exception {

        StoreFile sp = new StoreFile();

        JFileChooser fileChooser = new JFileChooser();
        fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
        fileChooser.showDialog(new JLabel(), "选择");

        String imgPath = null;
        File file = fileChooser.getSelectedFile();
        if (file.isFile()) {
            imgPath = file.getAbsolutePath();
        }

        // String imgPath="C:\\Users\\Administrator\\Pictures\\img12.jpg";
        //String wordPath="d:\\测试文档.docx";
        sp.storeImg(imgPath);
        //sp.storeImg(wordPath);
        //sp.readImg("D://数据库.jpg", 1);  //这里的1为要传入的参数：读取文件的id
        //sp.readImg("D://数据库.docx", 8);
    }

    public void initDB() {
        try {
            // Load Driver
            Class.forName(dbDriver).newInstance();
            // Get connection
            con = DriverManager.getConnection(dbURL,
                    dbUser, dbPassword);
        } catch (ClassNotFoundException e) {
            System.out.println(e.getMessage());
        } catch (SQLException ex) {
            // handle any errors
            System.out.println("SQLException: " + ex.getMessage());
            System.out.println("SQLState: " + ex.getSQLState());
            System.out.println("VendorError: " + ex.getErrorCode());

        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }

    /**
     * 将指定路径的文件(比如：图片，word文档等)存储到数据库
     *
     * @param strFile 要存放到数据库的文件路径，如D:\\a.jpg
     */
    public void storeImg(String strFile) throws Exception {
        int id = 0;
        File file = new File(strFile);
        FileInputStream fis = new FileInputStream(file);
        try {
            ps = con.prepareStatement("insert into PIC values (?,?,?)");
            ps.setInt(1, id);
            ps.setString(2, file.getName());
            ps.setBinaryStream(3, fis, (int) file.length());
            ps.executeUpdate();
            System.out.println("file insert success ");
        } catch (SQLException e) {
            System.out.println("SQLException: "
                    + e.getMessage());
            System.out.println("SQLState: "
                    + e.getSQLState());
            System.out.println("VendorError: "
                    + e.getErrorCode());
            e.printStackTrace();
        } finally {
            ps.close();
            fis.close();
            con.close();
        }
    }

    /**
     * 将存储在数据库中的文件(比如：图片，word文档等)读取到指定路径
     *
     * @param path 从数据库里读取出来的文件存放路径 如D:\\a.jpg
     * @param id   数据库里记录的id
     */
    public void readImg(String path, int id) throws Exception {
        initDB();   //建立与数据库的连接
        byte[] buffer = new byte[4096];
        FileOutputStream outputImage = null;
        InputStream is = null;
        try {
            ps = con.prepareStatement("select img from pic where id =?");
            ps.setInt(1, id);
            ResultSet rs = ps.executeQuery();
            rs.next();
            File file = new File(path);
            if (!file.exists()) {
                file.createNewFile();
            }
            outputImage = new FileOutputStream(file);
            Blob blob = rs.getBlob("img");   //img为数据库存放图片字段名称
            is = blob.getBinaryStream();
            int size = 0;
            while ((size = is.read(buffer)) != -1) {
                outputImage.write(buffer, 0, size);
            }
            System.out.println("file read success ");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            is.close();
            outputImage.close();
            ps.close();
            con.close();
        }
    }
}